package server;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

public class RequestProcessor extends Thread {

    private Socket socket;
    private Mapper mapper;

    public RequestProcessor(Socket socket, Mapper mapper) {
        this.socket = socket;
        this.mapper = mapper;
    }

    @Override
    public void run() {
        try {
            InputStream inputStream = socket.getInputStream();
            Mapper.MappedHost defaultHost = mapper.getDefaultHost();


            // 封装Request对象和Response对象
            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());

            // 获取项目访问URL ，例如: /web_demo
            String webAppUrl = request.getUrl();
            if (!"/".equals(request.getUrl())) {
                webAppUrl = "/" + request.getUrl().split("/")[1];
            }

            // 获取Context
            Mapper.MappedContext context = defaultHost.getContext(webAppUrl);
            if (context == null) {
                response.output(HttpProtocolUtil.getHttpHeader404());
                return;
            }
            // 去除工程名的URL
            String resourceUrl = request.getUrl().substring(webAppUrl.length());

            // 获取Wrapper中的servlet，如果warpper不存在可能是静态资源
            Mapper.MappedWrapper wrapper = context.getWrapper(resourceUrl);
            if (wrapper == null) {
                response.outputHtml(context.object.docBase + "/" + resourceUrl);
                return;
            }
            Servlet servlet = wrapper.object.getServlet();
            if (servlet == null) {
                // 静态资源处理
                response.outputHtml(context.object.docBase + "/" + resourceUrl);
            } else {
                // 动态资源servlet请求
                servlet.service(request, response);
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}
